<?php

namespace Biz\service\activity;

use Biz\cache\FullShipping as cFullShipping;
use Biz\model\activity\FullShipping as mFullShipping;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\model\activity\FullShippingGoods as mFullShippingGoods;
use Biz\service\Goods as sGoods;
use Biz\service\search\Goods as GoodsSearch;
use Biz\service\SearchGoods;
use Biz\tools\ShopArea;
use Biz\service\esSearch\Goods as esGoods;
/**
 * @deprecated
 */
class FullShipping
{

    const ICON_FULL_SHIPPING = 'http://img.hhz1.cn/Op-imageShow/6fe03302o01000000p9skvf?iv=1'; // 满包邮

    /**
     *
     * @param array $shopIdsArr ["shop_id"=>["goods_id1","goods_id2"],"shop_id2"=>["goods_id3","goods_id4"...]...]
     * @param string $areaCode
     * @return array
     */
    public static function quickGetFormatInfos($shopIdsArr, $areaCode, $withActivityText = false)
    {
        $areaCodeArr = ShopArea::getAreaCodeArr($areaCode);
        $provinceId = ($areaCodeArr && $areaCodeArr[0]) ? $areaCodeArr[0] : 0;
        $shopIds = array_keys($shopIdsArr);
        $shippingList = self::getShippingList($shopIds);
        $result = [];
        foreach ($shopIdsArr as $shopId => $goodsIds) {
            if (isset($shippingList[$shopId]) && $shippingList[$shopId] && isset($shippingList[$shopId]['id']) && $shippingList[$shopId]['is_happening']) {
                $info = $shippingList[$shopId];
                $unitStr = ($info['type'] == mFullShipping::TYPE_TOTAL_PIECES) ? '件' : '元';
                $shippingGoodsIds = $info['goods_ids'] ? json_decode($info['goods_ids'], true) : [];
                $provinceArr = json_decode($info[$provinceId], true);
                $planInfos = json_decode($info['planinfo'], true);
                if (isset($info[$provinceId]) && $info[$provinceId]) {
                    $totalUnit = ($info['type'] == mFullShipping::TYPE_TOTAL_PIECES) ? (int)$provinceArr['total_unit'] : $provinceArr['total_unit'];
                    $formatDatas = [
                        'id' => $info['id'],
                        'type_id' => ActivityInfo::ACTIVITY_TYPE_FULL_SHIPPING,
                        'type_name' => $info['title'],
                        'icon' => self::ICON_FULL_SHIPPING,
                        'title' => "满" . $totalUnit . $unitStr . "包邮",
                        'desc' => "满" . $totalUnit . $unitStr . "包邮，" . str_replace(",", "、", $provinceArr['province_desc']),
                        'params' => null
                    ];
                } else {
                    $planInfosUnitArr = array_column($planInfos, null, 'total_unit');
                    $minFullShipping = $planInfosUnitArr[min(array_keys($planInfosUnitArr))];
                    $totalUnit = ($info['type'] == mFullShipping::TYPE_TOTAL_PIECES) ? (int)$minFullShipping['total_unit'] : $minFullShipping['total_unit'];
                    $formatDatas =
                        [
                            'id' => $info['id'],
                            'type_id' => ActivityInfo::ACTIVITY_TYPE_FULL_SHIPPING,
                            'type_name' => $info['title'],
                            'icon' => self::ICON_FULL_SHIPPING,
                            'title' => "部分地区满" . $totalUnit . $unitStr . "包邮",
                            'desc' => "满" . $totalUnit . $unitStr . "包邮，" . str_replace(",", "、", $minFullShipping['province_desc']),
                            'params' => null
                        ];
                }
                foreach ($planInfos as $planInfo) {
                    $totalUnit = ($info['type'] == mFullShipping::TYPE_TOTAL_PIECES) ? (int)$planInfo['total_unit'] : $planInfo['total_unit'];
                    $strDesc = "满" . $totalUnit . $unitStr . "包邮，" . str_replace(",", "、", $planInfo['province_desc']);
                    if (!isset($formatDatas['params']['desc'])) {
                        $formatDatas['params']['desc'] = '';
                    }
                    if ($formatDatas['params']['desc']) {
                        $formatDatas['params']['desc'] .= "\n" . $strDesc;
                    } else {
                        $formatDatas['params']['desc'] .= $strDesc;
                    }
                }
                if ($withActivityText) $formatDatas['activity_text'] = "活动时间: " . date("Y.m.d", strtotime($info['start_time'])) . " - " . date("Y.m.d", strtotime($info['end_time']));
                foreach ($goodsIds as $goodsId) {
                    if ($info['all_goods']) {
                        $result[$shopId][$goodsId] = $formatDatas;
                    } else {
                        if ($shippingGoodsIds && !in_array($goodsId, $shippingGoodsIds)) {
                            $result[$shopId][$goodsId] = [];
                        } else {
                            $result[$shopId][$goodsId] = $formatDatas;
                        }
                    }
                }
            } else {
                foreach ($goodsIds as $goodsId) {
                    $result[$shopId][$goodsId] = [];
                }
            }
        }
        return $result;
    }

    /**
     * 获取商品满包邮的活动列表
     * @param $shopId 店铺id
     * @param $goodsId 商品id
     * @return array
     */
    public static function FullShippingList($shopId, $goodsId)
    {
        $shippingList = self::getShippingList([$shopId]);
        $Rst = [];
        foreach ($shippingList as $shopId => $info) {
            if ($info['is_happening']) {
                $unitStr = ($info['type'] == mFullShipping::TYPE_TOTAL_PIECES) ? '件' : '元';
                $shippingGoodsIds = $info['goods_ids'] ? json_decode($info['goods_ids'], true) : [];
                $hasShipping = false;
                if ($info['all_goods']) {
                    $hasShipping = true;
                } else if ($shippingGoodsIds && in_array($goodsId, $shippingGoodsIds)) {
                    $hasShipping = true;
                }
                if ($hasShipping) {
                    $planInfo = json_decode($info['planinfo'], true);
                    foreach ($planInfo as $row) {
                        $totalUnit = ($info['type'] == mFullShipping::TYPE_TOTAL_PIECES) ? (int)$row['total_unit'] : $row['total_unit'];
                        $Rst[$shopId][] = [
                            'id' => $row['id'],
                            'type_id' => ActivityInfo::ACTIVITY_TYPE_FULL_SHIPPING,
                            'type_name' => ActivityInfo::ACTIVITY_TYPES_MAPS[ActivityInfo::ACTIVITY_TYPE_FULL_SHIPPING],
                            'icon' => self::ICON_FULL_SHIPPING,
                            'title' => "满" . $totalUnit . $unitStr . "包邮",
                            'desc' => "满" . $totalUnit . $unitStr . "包邮，" . str_replace(",", "、", $row['province_desc']),
                            'params' => null
                        ];
                    }
                }
            }
        }

        return $Rst;
    }

    public static function getShippingList($shopIds)
    {
        list($cacheDatas, $noCacheShopIds) = cFullShipping::getCaches($shopIds);
        $noCacheDatas = $noCacheShopIds ? self::getItemByShopIds($noCacheShopIds) : [];
        $data = $cacheDatas + $noCacheDatas;
        return $data;
    }

    private static function getItemByShopIds($shopIds, $item = '')
    {
        $fullShippingInfos = mFullShipping::getRecentlyShipping($shopIds);
        $Rst = [];
        foreach ($shopIds as $shopId) {
            if (isset($fullShippingInfos[$shopId])) {
                //有未结束的满包邮
                $cacheData = self::formatCache($fullShippingInfos[$shopId]);
                if ($item) {
                    $Rst[$shopId] = isset($cacheData[$item]) ? $cacheData[$item] : null;
                } else {
                    $Rst[$shopId] = $cacheData;
                }
                if ($fullShippingInfos[$shopId]['expire']) {
                    cFullShipping::setCache($shopId,
                        $cacheData,
                        $fullShippingInfos[$shopId]['expire']);
                }

            } else {
                //未设置满包邮
                cFullShipping::setCache($shopId, [0 => null]);
            }
        }
        return $Rst;
    }

    private static function formatCache($fullShippingInfo)
    {
        $formatCache = $fullShippingInfo;
        if ($fullShippingInfo['is_happening']) {
            foreach ($fullShippingInfo['planinfo'] as $planinfos) {
                foreach ($planinfos['province_ids'] as $province_id) {
                    $formatCache[$province_id] = json_encode($planinfos, JSON_UNESCAPED_UNICODE);
                }
            }
        }
        $formatCache['planinfo'] = json_encode($formatCache['planinfo'], JSON_UNESCAPED_UNICODE);
        $formatCache['goods_ids'] = $fullShippingInfo['goods_ids'] ? json_encode($fullShippingInfo['goods_ids'], JSON_UNESCAPED_UNICODE) : '';
        return $formatCache;
    }

    /**
     * 根据满包邮活动id获取商品
     * @param $shippingId
     * @param $sortType
     * @param $page
     * @param $pageSize
     * @param $areaCode
     * @return array
     * @throws \Exception
     */
    public static function getFullShippingGoodsByShippingId($shippingId, $sortType, $page, $pageSize, $areaCode)
    {
        $result = [];
        $info = mFullShipping::getInfoById($shippingId);
        if ($info) {
            $shopId = $info['shop_id'];
            $data = self::getShippingList([$shopId]);
            $info = isset($data[$shopId]) ? $data[$shopId] : [];
            $res = [];
            if ($info) {
                if ($info['all_goods']) {
                    $res = SearchGoods::searchEntrance(['shop_id' => $shopId, 'source' => esGoods::SOURCE_APP], esGoods::SCENES_FULL_SHIPPING, $sortType, $page, $pageSize);
                    // todo 搜索切换es待删除
//                    $res = GoodsSearch::searchByConditions(['shop_id' => $shopId], $sortType, $page, $pageSize);
                } else {
                    $goodsIds = $info['goods_ids'] ? json_decode($info['goods_ids'], true) : [];
                    if ($goodsIds) {
                        // todo 搜索切换es待删除
//                        $res = GoodsSearch::searchGoodsByActivityId($shippingId, $page, $sortType, $pageSize);

                        // es 方法调用
                        $where['activity'] = esGoods::ACTIVITY_TYPE_FULL_SHIPPING . $shippingId;
                        $where['source'] = esGoods::SOURCE_APP;
                        $res = SearchGoods::searchEntrance($where, esGoods::SCENES_FULL_SHIPPING, $sortType, $page, $pageSize);// $res['rows'] = ['goods_id1', 'goods_id2'];

                    }
                }
            }
            if ($res) {
                $goodsIds = $res['rows'];
                $list = sGoods::goods($goodsIds, sGoods::FIELDS_GROUP_LIST, ['area_code' => $areaCode]);
                $result = ['list' => array_values($list), 'is_over' => $res['is_over']];
            }
        }
        return $result;
    }


    public static function getShippingByGoodsIdForSolor($goodsId)
    {
        $result = [];
        $list = mFullShippingGoods::getShippingByGoodsId($goodsId, ['shipping_id']);
        if ($list) {
            $shippingIds = array_column($list, 'shipping_id');
            $result = [$goodsId => $shippingIds];
        }
        return $result;
    }

    /**
     *
     * 根据用户省份ID,商户ID,购物车中商品的总金额
     * 计算满减包邮的差额并返回格式化信息
     *
     * @param       $provinceId
     * @param array $data
     * [
     *      22(shopId)=>[
     *                  12(goodsId)=>[
     *                          'goods_amount'=>100, //总价格
     *                          'buy_num'=>2, //总数量
     *                          ],
     *                   13(goodsId)=>[
     *                          'goods_amount'=>22,
     *                          'buy_num'=>1
     *                          ],
     *                  ],
     *      24(shopId)=>[
     *                  112(goodsId)=>[
     *                          'goods_amount'=>10,
     *                          'buy_num'=>5
     *                          ],
     *                   113(goodsId)=>[
     *                          'goods_amount'=>202,
     *                          'buy_num'=>1
     *                          ],
     *                  ],
     * ]
     *
     * @return array
     *
     */
    public static function calGapFeeInfoInCart($areaCode, $data = [])
    {
        $areaCodeArr = ShopArea::getAreaCodeArr($areaCode);
        $provinceId = $areaCodeArr[0];
        $result = [];
        $shopIds = array_keys($data);
        $shippingList = self::getShippingList($shopIds);
        foreach ($shippingList as $shopId => $shippingInfo) {
            if (isset($shippingInfo[$provinceId]) && $shippingInfo['is_happening'] && $shippingInfo[$provinceId]) {
                $planInfo = json_decode($shippingInfo[$provinceId], true);
                $goodsIds = array_keys($data[$shopId]);

                $goodsAmount = 0; //满包邮商品金额
                $buyNums = 0;//满包邮商品购买的件数
                $canShippingGoodsIds = [];//可以满包邮的商品ids
                if ($shippingInfo['all_goods']) {
                    foreach ($data[$shopId] as $goodsId => $row) {
                        $goodsAmount = bcadd($goodsAmount, $row['goods_amount'], 2);
                        $buyNums = bcadd($buyNums, $row['buy_num']);
                    }
                    $canShippingGoodsIds = $goodsIds;
                } else {
                    $shippingInfoGoodsIds = $shippingInfo['goods_ids'] ? json_decode($shippingInfo['goods_ids'], true) : [];
                    $canShippingGoodsIds = array_intersect($goodsIds, $shippingInfoGoodsIds);
                    foreach ($data[$shopId] as $goodsId => $row) {
                        if (in_array($goodsId, $canShippingGoodsIds)) {
                            $goodsAmount = bcadd($goodsAmount, $row['goods_amount'], 2);
                            $buyNums = bcadd($buyNums, $row['buy_num']);
                        }
                    }
                }
                if ($shippingInfo['type'] == mFullShipping::TYPE_TOTAL_AMOUNT) {
                    $gapFee = bcsub($planInfo['total_unit'], $goodsAmount, 2);
                    $gapFee = $gapFee > 0 ? $gapFee : 0;
                    $result[$shopId] = [
                        'type' => mFullShipping::TYPE_TOTAL_AMOUNT,
                        'gap_pieces' => 0,
                        'gap_fee' => $gapFee,
                        'primary_id' => $planInfo['id'],
                        'free_goods_ids' => $canShippingGoodsIds,
                        'all_goods' => $shippingInfo['all_goods'],
                    ];
                }
                if ($shippingInfo['type'] == mFullShipping::TYPE_TOTAL_PIECES) {
                    $gapPieces = bcsub($planInfo['total_unit'], $buyNums);
                    $gapPieces = $gapPieces > 0 ? $gapPieces : 0;
                    $result[$shopId] = [
                        'type' => mFullShipping::TYPE_TOTAL_PIECES,
                        'gap_pieces' => $gapPieces,
                        'gap_fee' => 0,
                        'primary_id' => $planInfo['id'],
                        'free_goods_ids' => $canShippingGoodsIds,
                        'all_goods' => $shippingInfo['all_goods'],
                    ];
                }

            }
        }
        return $result;

    }

    /**
     * 获取商品是否参与满包邮的活动
     * @param int $shopId 店铺id
     * @param string $areaCode 地区code
     * @param array $goodsIds 商品id集合
     * @return array
     */
    public static function FullShippingMap($shopId, $areaCode, $goodsIds)
    {
        $areaCodeArr = ShopArea::getAreaCodeArr($areaCode);
        $provinceId = isset($areaCodeArr[0]) ? $areaCodeArr[0] : 0;
        $shippingList = self::getShippingList([$shopId]);
        $map = [];
        $planInfo = [];
        $detail = [];
        $total = 0;
        $type = 0;
        if ($goodsIds) {
            foreach ($goodsIds as $goodsId) {
                foreach ($shippingList as $shopId => $info) {
                    if ($info['is_happening'] && isset($info[$provinceId])) {
                        $provinceArr = json_decode($info[$provinceId], true);
                        $unitStr = ($info['type'] == mFullShipping::TYPE_TOTAL_PIECES) ? '件' : '元';
                        $planInfo = json_decode($info['planinfo'], true);
                        $paramsDesc = [];
                        foreach ($planInfo as $v) {
                            $total_unit = $info['type'] == mFullShipping::TYPE_TOTAL_PIECES ? intval($v['total_unit']) : $v['total_unit'];
                            $strDesc = "满" . $total_unit . $unitStr . "包邮，" . str_replace(",", "、", $v['province_desc']);
                            $paramsDesc[] = $strDesc;
                        }
                        $paramsDescString = implode("\n", $paramsDesc);
                        if (isset($info[$provinceId]) && $info[$provinceId]) {
                            $total = $info['type'] == mFullShipping::TYPE_TOTAL_PIECES ? intval($provinceArr['total_unit']) : $provinceArr['total_unit'];
                            $detail = [
                                'id' => $info['id'],
                                'type_id' => ActivityInfo::ACTIVITY_TYPE_FULL_SHIPPING,
                                'type_name' => $info['title'],
                                'icon' => self::ICON_FULL_SHIPPING,
                                'title' => "满" . $total . $unitStr . "包邮",
                                'desc' => "满" . $total . $unitStr . "包邮，" . str_replace(",", "、", $provinceArr['province_desc']),
                                'activity_text' => "活动时间: " . date("Y.m.d", strtotime($info['start_time'])) . " - " . date("Y.m.d", strtotime($info['end_time'])),
                                'params' => [
                                    'desc' => $paramsDescString,
                                ],
                            ];
                        } else {
                            $planInfosUnitArr = array_column($planInfo, null, 'total_unit');
                            $minFullShipping = $planInfosUnitArr[min(array_keys($planInfosUnitArr))];
                            $total = $info['type'] == mFullShipping::TYPE_TOTAL_PIECES ? intval($minFullShipping['total_unit']) : $minFullShipping['total_unit'];
                            $detail = [
                                'id' => $info['id'],
                                'type_id' => ActivityInfo::ACTIVITY_TYPE_FULL_SHIPPING,
                                'type_name' => $info['title'],
                                'icon' => self::ICON_FULL_SHIPPING,
                                'title' => "部分地区满" . $total . $unitStr . "包邮",
                                'desc' => "满" . $total . $unitStr . "包邮，" . str_replace(",", "、", $minFullShipping['province_desc']),
                                'activity_text' => "活动时间: " . date("Y.m.d", strtotime($info['start_time'])) . " - " . date("Y.m.d", strtotime($info['end_time'])),
                                'params' => [
                                    'desc' => $paramsDescString,
                                ],
                            ];
                        }
                        $type = $info['type'];

                        $shippingGoodsIds = $info['goods_ids'] ? json_decode($info['goods_ids'], true) : [];
                        $hasShipping = false;
                        if ($info['all_goods']) {
                            $hasShipping = true;
                        } else if ($shippingGoodsIds && in_array($goodsId, $shippingGoodsIds)) {
                            $hasShipping = true;
                        }
                        if ($hasShipping) {
                            $map[] = $goodsId;
                        }
                    }
                }
            }
        }
        return compact('map', 'total', 'type', 'detail', 'planInfo');
    }
}